<!-- 我的主页 -->
<template>
	<view class="container">
		<view class="header" @click="login" :style="{paddingTop:navBarTop + 'px'}">
			<view class="header-item" v-if="userInfo.avatarUrl">
				<view class="" v-if="userInfo.officiallyCertified==1||userInfo.officiallyCertified==0">
					<u-avatar :src="userInfo.businessLogo" size='60' shape="circle"></u-avatar>
				</view>
				<view class="" v-else>
					<u-avatar :src="userInfo.avatarUrl" size='60' shape="circle"></u-avatar>
				</view>
				<view class="header-item-title">
					<view class="title-name">
						<view class="name-top" v-if="userInfo.officiallyCertified==1||userInfo.officiallyCertified==0">
							{{userInfo.businessName.length>8? userInfo.businessName.substring(0,8)  + ".." : userInfo.businessName}}
						</view>
						<view class="name-top" v-else>
							{{userInfo.nickName?userInfo.nickName:'微信用户'}}
						</view>

						<view class="name-bot" v-if="userInfo.officiallyCertified==0"
							style="background: linear-gradient(to right bottom, #0055ff, #00aaff, #00ffff);">
							商家
						</view>
						<view class="name-bot" v-else-if='userInfo.officiallyCertified==1'
							style="background: linear-gradient(to right bottom, #ff0000, #ff5500, #ffff00);">
							认证商家
						</view>
						<view class="name-bot" v-else
							style="background: linear-gradient(to right bottom, #c98a47, #dca963, #dcc193);">
							个人
						</view>
					</view>
					<view class="" style="margin: 10px 10px; font-size: 12px; " @click="mydetail">
						<span
							style="background-color: rgba(242, 215, 71, 1); padding: 2px 8px; border-radius: 8px; color: #574b0e;">账号设置</span>
						<view class="">

						</view>
					</view>
				</view>

			</view>
			<view class="header-item" v-else>
				<view class="">
					<u-avatar :src="userInfo.avatarUrl" shape="circle"></u-avatar>
				</view>
				<view class="" style="margin-left: 10px;">
					点击登录
				</view>
			</view>

		</view>
		<u-tabs :list="list1" lineWidth="20" lineHeight="7" :lineColor="`url(${lineBg}) 100% 100%`" :activeStyle="{
				        color: '#303133',
				        fontWeight: 'bold',
				        transform: 'scale(1.05)'
				    }" :inactiveStyle="{
				        color: '#606266',
				        transform: 'scale(1)'
				    }" itemStyle="padding-left: 15px; padding-right: 15px; height: 34px;" @click="tabswitch">
		</u-tabs>
		<u-empty v-if="this.contenlist.length==0 && this.tabindex==0" text='发布列表为空,快去发布一个吧' mode="list"
			icon="http://cdn.uviewui.com/uview/empty/list.png">
		</u-empty>
		<u-empty v-else-if="this.contenlist.length==0 && this.tabindex==1" text='暂无收藏,快去收藏一个心仪的消息吧' mode="data"
			icon="http://cdn.uviewui.com/uview/empty/data.png">
		</u-empty>
		<scroll-view v-else scroll-y :style="{ height: `calc(100vh - ${navBarTop}px - 75px - 34px - 60px)`}"
			@scrolltolower='scrolltolower'>
			<view style="display: flex; justify-content: center; " v-for="(item,index) in contenlist" :key="index">
				<view class="list-item" @click="messdetail(item)">
					<view class="" style="position: absolute; top: 0; right: 0;" v-if="tabindex==2">
						<view class="iconfont icon-yishangjia" style="font-size: 55px; color: #00aa7f;"
							v-if="item.display==0">
						</view>
						<view class="iconfont icon-yixiajia" style=" font-size: 55px; color: #ff557f;" v-else>
						</view>

					</view>
					<view class="itme-top">
						<view class="" style="margin-right:5px;">
							<u-avatar :src="item.nickUrl" shape="circle"></u-avatar>
						</view>
						<view class="">
							<view class="" style="font-size: 13px; font-weight: bold;">
								{{item.nickName.length>8? item.nickName.substring(0,8)  + ".." : item.nickName}}
							</view>
							<view class="" style="font-size: 11px; color: #b5b5b5;">
								{{item.timestr}}
							</view>
						</view>
					</view>
					<view class="info_label">
						<view class="two__item">
							{{item.dynamicType==1?'房屋租赁':''}}
							{{item.dynamicType==3?'公司招聘':''}}
							{{item.dynamicType==2?'个人简历':''}}
							{{item.dynamicType==4?'我有好货':''}}
							{{item.dynamicType==6?'社区服务':''}}
							{{item.dynamicType==7?'社区团购':''}}
							{{item.dynamicType==8?'社区公益':''}}
							{{item.dynamicType==9?'教育服务':''}}
							{{item.dynamicType==10?'养老服务':''}}
						</view>
						<view class="two__item" v-for="obj in item.shoplist" :key="obj">
							{{obj}}
						</view>
					</view>
					<view class="item-two">
						<view class="" style="width: calc(100% - 140px - 10px);">
							<view class="" style="font-size: 15px; font-weight: bold;">
								{{ item.topic ?  (item.topic && item.topic.length > 8 ? item.topic.substring(0, 8) + '...' : item.topic) : (item.content && item.content.length > 8 ? item.content.substring(0, 8) + '...' : item.content) }}
							</view>
							<view class="" style="font-size: 14px; ">
								{{item.content.length > 30? item.content.substring(0,30) + '...' : item.content}}
							</view>
						</view>
						<view class="">
							<u--image :src="item.headImages" width='140' height='80' radius='5'></u--image>
						</view>
					</view>
					<view class="item-three" v-if="item.address">
						<view class="">
							<u-icon name="map" size="12" style="margin-right: 5px;"></u-icon>
						</view>
						<view class="" style="font-size: 12px; color: #b5b5b5;">
							{{item.address}}
						</view>
					</view>
					<view class="item-four" v-if="item.price">
						{{item.price?(item.price.length>10? item.price.substring(0,10)  + ".." : item.price):''}}{{ item.salaryType ? (item.salaryType == 1 ? '/天' : (item.salaryType == 2 ? '/月' : (item.salaryType == 3 ? '/年' : ''))) : '' }}
					</view>
					<view class="item-five" v-if="tabindex==0">
						<view class="five-item" >
							<view class="">
								<u-icon name="edit-pen-fill" size="20" style="margin-right: 5px;"></u-icon>
							</view>
							<view class="" @click.stop="edit(item)">
								编辑
							</view>
						</view>
						<view class="" style="display: flex; align-items: center;" @click.stop="del(item)">
							<view class="">
								<u-icon name="trash" size="20" style="margin-right: 5px;"></u-icon>
							</view>
							<view class="">
								删除
							</view>
						</view>
					</view>
					<view class="item-five" v-if="tabindex==2">
						<view class="five-item" @click.stop="delshelves(item)" v-if="item.display==0">
							<u-button type="error" icon="trash" text="下架"></u-button>
						</view>
						<view class="five-item" @click.stop="listing(item)" v-else>
							<u-button type="success" icon="shopping-cart" text="上架"></u-button>
						</view>

					</view>
					<!-- <view class="item-five" v-else-if='tabindex==2' style="color: #b9b9b9;">
						正在审核中
					</view> -->
				</view>
			</view>
		</scroll-view>
		<layout>
		</layout>
		<u-modal :show="showtips" title="绑定提示" @confirm='modalconfirm'>
			<view class="slot-content">
				<view class="" @click="showcomp=true">
					<view class="">
						你还未绑定所属社区，请先绑定社区。
					</view>
					<u--input v-model="region" :disabled='true' disabledColor='#fff' placeholder="请选择所属区域" border="none"
						suffixIcon="arrow-right" style="margin: 20px;"></u--input>
				</view>
			</view>
		</u-modal>
		<u-picker :show="showcomp" ref="uPicker" @cancel='showcomp = false' keyName="label" :columns="columns"
			@confirm="confirm" @change="changeHandler"></u-picker>
	</view>
</template>

<script>
	import {
		formatTimeAgo
	} from '../../utils/utils.js'
	import layout from '../layout/layout.vue'
	export default {
		data() {
			return {
				region: "", //社区名字
				communityId: '', //选择的社区id
				showtips: false, //提示绑定社区弹出框
				columns: [],
				columnData: [],
				showcomp: false, //社区选择弹框
				contenlist: [], //列表数据
				query: {
					pageNum: 1,
					pageSize: 10,
				},
				tabindex: 0, //tab状态栏切换
				navBarTop: 50, //头像距离顶部的距离
				userInfo: {}, //存储用户信息
				lineBg: "",
				list1: [{
					name: '我的发布',
				}, {
					name: '我的收藏',
				}, ]
			};
		},
		created() {
			//从本地同步拿到用户详细信息
			this.userInfo = uni.getStorageSync('userinfokey')
			if (this.userInfo.communityAdmin == 1) {
				this.list1.push({
					name: '社区审核'
				})
			}
		},
		mounted() {
			const that = this
			this.$request(`/select/area`, 'get').then(
				res => {
					that.columns = res.data.data.columns
					that.columnData = res.data.data.columnData

				})
			//获取页面顶部距离
			let menuButtonInfo = uni.getMenuButtonBoundingClientRect();
			this.navBarTop = menuButtonInfo.top + menuButtonInfo.height;
			uni.$emit('update', {
				active: 3
			}) // 触发事件并传递参数	
			this.tablist() //请求数据列表
		},
		components: {
			layout
		},
		onLoad(options) {},
		methods: {
			modalconfirm() {
				if (this.communityId=='') {
					uni.showToast({
						title: '请先绑定社区',
						icon: 'none'
					});
					return;
				}
				const data = {
					communityId: this.communityId,
					communityName: this.region,
				}
				this.$request(`/member/edit`, 'post', data).then(
					res => {
						uni.showToast({
							title: '绑定成功',
						})
						this.userInfo.communityName = this.region
						this.userInfo.communityId = this.communityId
						uni.setStorage({
							key: 'userinfokey',
							data: this.userInfo,
							success: function() {
								console.log(
									'修改用户信息成功');
							}
						});
						this.showtips = false
					})



			},
			confirm(e) {
				this.communityId = e.value[1].id
				this.region = e.value[1].label
				this.showcomp = false
			},
			changeHandler(e) {
				const {
					columnIndex,
					value,
					values, // values为当前变化列的数组内容
					index,
					// 微信小程序无法将picker实例传出来，只能通过ref操作
					picker = this.$refs.uPicker
				} = e
				// 当第一列值发生变化时，变化第二列(后一列)对应的选项
				if (columnIndex === 0) {
					// picker为选择器this实例，变化第二列对应的选项
					picker.setColumnValues(1, this.columnData[index])
				}
			},
			//我的发布列表
			myfindpage() {
				this.$request(`/my/release/findPage`, 'post', this.query).then(
					res => {
						const arrlist = res.data.data.list.map(item => ({
							...item,
							shoplist: item.labels == '' || !item.labels ? [] : item.labels.split(","),
							timestr: formatTimeAgo(item.updateTime)
						}));
						this.contenlist = this.contenlist.concat(arrlist)
					})
			},
			//我的收藏列表
			myfavoritepage() {
				this.$request(`/my/favorite/findPage`, 'post', this.query).then(
					res => {
						const arrlist = res.data.data.records.map(item => ({
							...item,
							shoplist: item.labels == '' || !item.labels ? [] : item.labels.split(","),
							timestr: formatTimeAgo(item.updateTime)

						}));
						this.contenlist = this.contenlist.concat(arrlist)
					})
			},
			// 社区审核列表
			adminauditing() {
				this.$request(`/my/audit/findPage`, 'post', this.query).then(
					res => {
						const arrlist = res.data.data.list.map(item => ({
							...item,
							shoplist: item.labels == '' || !item.labels ? [] : item.labels.split(","),
							timestr: formatTimeAgo(item.updateTime)

						}));
						this.contenlist = this.contenlist.concat(arrlist)
					})
			},
			//上架
			listing(e) {
				const that = this
				uni.showModal({
					title: '上架提示',
					content: '您是否准备上架当前所选的的消息,点击确定进行上架',
					success: function(res) {
						if (res.confirm) {
							const data = {
								id: e.id,
								dynamicType: e.dynamicType
							}
							that.$request(`/mine/setUp`, 'post', data).then(
								res => {
									if (res.data.data) {
										uni.showToast({
											title: '上架成功',
										})
										that.query.pageNum = 1
										that.contenlist = []
										that.tablist()
									}
								})

						} else if (res.cancel) {
							return
						}
					}
				});
			},
			//下架
			delshelves(e) {
				const that = this
				uni.showModal({
					title: '下架提示',
					content: '您是否准备下架当前所选的的消息,点击确定进行下架,下架之后用户将无法查看此消息',
					success: function(res) {
						if (res.confirm) {
							const data = {
								id: e.id,
								dynamicType: e.dynamicType
							}
							that.$request(`/mine/setDown`, 'post', data).then(
								res => {
									if (res.data.data) {
										uni.showToast({
											title: '下架成功',
										})
										that.query.pageNum = 1
										that.contenlist = []
										that.tablist()
									}
								})

						} else if (res.cancel) {
							return
						}
					}
				});
			},
			// 状态栏切换时处理
			tabswitch(e) {
				this.tabindex = e.index
				this.query.pageNum = 1
				this.contenlist = []
				this.tablist()
			},
			tablist() {
				if (this.tabindex == 0) {
					this.myfindpage()
				} else if (this.tabindex == 1) {
					this.myfavoritepage()
				} else if (this.tabindex == 2) {
					this.adminauditing()
				}
			},
			scrolltolower() {
				this.query.pageNum++
				this.tablist()
			},
			// 删除
			del(e) {
				const that = this
				uni.showModal({
					title: '删除提示',
					content: '此操作将永久删除此条数据,不可恢复,是否确定删除',
					success: function(res) {
						if (res.confirm) {
							const data = {
								id: e.id,
								dynamicType: e.dynamicType
							}
							that.$request(`/mine/del`, 'post', data).then(
								res => {
									if (res.data.data) {
										uni.showToast({
											title: '删除成功',
										})
										that.query.pageNum = 1
										that.contenlist = []
										that.tablist()
									}
								})

						} else if (res.cancel) {
							return
						}
					}
				});
			},
			//编辑接口
			edit(e) {
				console.log(e);
				// console.log(e);
				const typeUrlMap = {
					1: '/pages/release/sublease_relepage',
					2: '/pages/release/resume_relepage',
					3: '/pages/release/recruit_relepage',
					4: '/pages/release/market_relepage',
					6: '/pages/release/community_relepage',
					7: '/pages/release/buying_relepage',
					8: '/pages/release/activity_relepage',
					9: '/pages/release/education_relepage',
					10: '/pages/release/elderly_relepage',
				};
				if (typeUrlMap[e.dynamicType]) {
					console.log(`${typeUrlMap[e.dynamicType]}?typeid=${encodeURIComponent(e.id)}`);
					console.log(e.dynamicType);
					uni.navigateTo({
						url: `${typeUrlMap[e.dynamicType]}?typeid=${encodeURIComponent(e.id)}`
					});
				} else {
					console.error('Unknown dynamicType:', e.dynamicType);
				}
			},
			//我的详情
			mydetail() {
				// if (this.userInfo.officiallyCertified == 1 || this.userInfo.officiallyCertified == 0) {
				// 	uni.navigateTo({
				// 		url: '/pages/detail/businessdetails?busid=' + encodeURIComponent(this.userInfo
				// 			.businessId)
				// 	});
				// } else {
				uni.navigateTo({
					url: '/pages/detail/userdetails'
				});
				// }

			},
			//消息详情
			messdetail(e) {
				const typeUrlMap = {
					1: '/pages/detail/subleasemessage_detail',
					2: '/pages/detail/resumemessage_detail',
					3: '/pages/detail/recruitmessage_detail',
					4: '/pages/detail/marketmessage_detail',
					6: '/pages/detail/communitymessage_detail',
					7: '/pages/detail/buying_detail',
					8: '/pages/detail/activity_detail',
					9: '/pages/detail/education_detail',
					10: '/pages/detail/elderly_detail',
				};

				const url = typeUrlMap[e.dynamicType];
				if (url) {
					uni.navigateTo({
						url: `${url}?typeid=${encodeURIComponent(e.id)}`,
						events: {
							reverseData: (data) => {
								if (data.data && this.tabindex == 1) {
									this.query.pageNum = 1
									this.contenlist = []
									this.tablist()
								}
							},

						},

					});
				} else {
					console.error('Unknown dynamicType:', e.dynamicType);
				}
			},
			//处理登录事件
			login() {
				const that = this;
				that.userInfo = uni.getStorageSync('userinfokey')
				//判断是否有token如果有当再次点击头像跳转到详情页
				if (that.userInfo.token) {
					// console.log('已存在token，无需执行uni-login');
					return;
				}
				// 登录api进行登录
				uni.login({
					provider: 'weixin',
					success: res => {
						// 用户唯一code码
						const code = res.code
						// 获取用户信息
						uni.getUserInfo({
							provider: 'weixin',
							success: res => {
								that.userInfo = res.userInfo
								// 拿到用户信息进行存储
								const data = {
									code: code,
									nickName: res.userInfo.nickName,
									avatarUrl: res.userInfo.avatarUrl,
								}
								//发送请求将用户信息存储后台
								that.$request(`/wechat/getaccountbycode`, 'post', data)
									.then(
										res => {
											if (!res.data.data.user.communityId) {
												that.showtips = true
											}
											const dataobj = {
												token: res.data.data.token,
												...res.data.data.user
											}

											that.userInfo = dataobj
											// 将用户信息和token存储到本地
											uni.setStorage({
												key: 'userinfokey',
												data: dataobj,
												success: function() {
													console.log(
														'存储用户信息成功');
												}
											});
											uni.showToast({
												title: '登录成功',
											})
											that.tablist()
											if (that.userInfo.communityAdmin == 1 && that.list1
												.length == 2) {
												that.list1.push({
													name: '社区审核'
												})
											}
										})
							},
							fail: err => {
								console.error('获取用户信息失败！' + JSON.stringify(err))
							}
						})
					},
					fail: err => {
						console.error(JSON.stringify(err))
					}
				})
			},

		}
	};
</script>

<style scoped lang="scss">
	.container {
		min-height: 100vh;
		background-color: #f5f5f5;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: flex-start;

		/* 禁止手动调整文本框大小 */
		::-webkit-scrollbar {
			width: 0px;
			/* 滚动条的宽度 */
		}

		::v-deep .u-input {
			margin: 20px !important;
		}

		.header {
			min-height: 50px;
			width: calc(100vw - 40px);
			background-color: #fee138;
			padding: 0 20px 15px;

			.header-item {
				height: 60px;
				display: flex;
				align-items: center;

				.header-item-title {
					height: 40px;
					display: flex;
					flex-direction: column;
					justify-content: space-between;

					.title-name {
						display: flex;
						align-items: center;
						height: 15px;

						.name-top {
							font-size: 18px;
							margin: 0 10px;
						}

						.name-bot {
							padding: 1px 3px;
							font-size: 12px;
							color: #fff;
							border-radius: 2px;
						}
					}
				}
			}
		}

		::v-deep .u-tabs {
			width: calc(100vw - 20px);
			padding: 0 10px;

		}

		.list-item {
			position: relative;
			padding: 10px;
			width: calc(95% - 20px);
			background-color: #fff;
			// height: 170px;
			border-radius: 10px;
			margin: 5px 0;




			.itme-top {
				height: 50px;
				display: flex;
				align-items: center;
				margin-bottom: 10px;
			}

			.info_label {
				display: flex;
				align-items: center;
				font-size: 12px;
				margin-bottom: 5px;
				margin-top: 5px;

				.two__item {
					padding: 2px 8px;
					margin-right: 3px;
					border-radius: 3px;
					color: #000;
					background-color: #fbeaa4;
				}

				:first-child {
					background-color: #fbc338;
				}
			}

			.item-two {
				display: flex;
				justify-content: space-between;
				margin-bottom: 10px;
			}

			.item-three {
				margin-bottom: 10px;
				display: flex;
				align-items: center;
			}

			.item-four {
				font-weight: 600;
				font-size: 17px;
				margin-bottom: 10px;
			}

			.item-five {
				display: flex;
				justify-content: flex-end;

				.five-item {
					display: flex;
					align-items: center;
					margin-right: 10px;

					::v-deep .u-button {
						height: 34px !important;
					}

				}
			}
		}
	}
</style>